<template>
  <van-index-bar :index-list="indexList">
    <section id="city-list" class="city-list-container" style="display: block">
      <section>
        <van-index-anchor index="定位" id="locate" class="city-title">定位城市</van-index-anchor>
        <div class="city-list city-list-inline clearfix">
          <div class="location-city">定位失败，请点击重试</div>
        </div>
      </section>

      <section class="history-city-list">
        <van-index-anchor index="最近" id="history" class="city-title">最近访问城市</van-index-anchor>
        <div class="city-list city-list-inline clearfix">
          <div class="city-item" data-nm="阿拉善盟" data-id="150" @click="changeCity('阿拉善盟')">阿拉善盟</div>
          <div class="city-item" data-nm="鞍山" data-id="151" @click="changeCity('鞍山')">鞍山</div>
        </div>
      </section>

      <section>
        <van-index-anchor index="热门" id="hot" class="city-title">热门城市</van-index-anchor>
        <div class="city-list city-list-inline clearfix">
          <div 
            class="city-item"
            v-for="c in hotCities"
            :key="c.id"
            @click="changeCity(c.name)"
          >{{c.name}}</div>
        </div>
      </section>

      <section>
        <div
          class="city-title city-title-letter"
          v-for="v,k,i in cities"
          :key="k"
        >
          <van-index-anchor :index="k">{{k}}</van-index-anchor>
          <div class="city-list city-list-block clearfix"
            v-for="c in v"
            :key="c.id"
          >
            <div class="city-item" @click="changeCity(c.name)">
              {{c.name}}
            </div>
          </div>
        </div>
      </section>
    </section>
  </van-index-bar>
</template>

<script>
import Vue from 'vue';
import {get} from '@u/http'

import { IndexBar, IndexAnchor } from 'vant';

Vue.use(IndexBar);
Vue.use(IndexAnchor);

export default {
  data() {
    return {
      indexList: ['定位', '最近', '热门'],
      hotCities: [],
      cities: []
    }
  },

  methods: {
    changeCity(city) {
      this.$store.dispatch('changeCity', city)
      this.$router.push('/')
    }
  },
  
  async mounted() {
    let result = await get({
      url: '/json/cities'
    })
    .then(result => {
      let {hotCities, cities} = result.data
      this.hotCities = hotCities
      this.cities = cities

      // 侧栏数据渲染
      let citiesIndex = Object.keys(cities)
      this.indexList = [
        ...this.indexList,
        ...citiesIndex
      ]
    })
  },
};
</script>

<style lang='stylus'>
.van-index-bar
  >div
    z-index: 10000
    span
      line-height 1.6
</style>